<?php
namespace App\Tools;
use App\Http\Controllers\Controller;
use QL\QueryList;
use GuzzleHttp\Client;

class Collection extends Controller{

	protected $queryObj = null;
	protected $searchUrl = ''; //小说网站搜索链接
	protected $is_book = true; //书籍是否存在

	public function __construct(){
		if(is_null($this->queryObj)){
			$this->queryObj = new QueryList;
		}
		
	}

	// 采集起点
	public function qidian($keyword){

		//基本结构
		$query = $this->queryObj;
		$this->searchUrl = 'https://www.qidian.com/search?kw=';
		$html = $this->getWebHtml($this->searchUrl.urlencode($keyword));

		// 搜查规则
		$rule = [
			'name'=>['.book-mid-info:first h4','text'],//
			'bookId'=>['.book-mid-info:first h4 a','data-bid'],//
		];
		$res = $query->query($html,$rule)->getData();

		// 判断是否搜查到
		if(empty($res) || $res[0]['name'] != $keyword){
			$this->is_book = false;
		}

		if($this->is_book != true){
			return false;
		}

		//获取书籍详细信息
		$bookUrl = "https://book.qidian.com/info/";
		$html = $this->getWebHtml($bookUrl.$res[0]['bookId'].'#Catalog');

		// 详细书籍规则
		$rule = [
			'name'=>['.book-info:first h1 em:first','text'],//书名
			'author'=>['.book-info:first .writer','text'],//作者
			'introduction'=>['.book-info:first .intro','text'],//简介
			'book_img'=>['#bookImg img','src'],//书图
			'words_num'=>['.book-info:first p em:first','text'],//字数
			// 'category'=>['#j-catalogWrap ul li a','html'],//章节
		];
		$res = $query->query($html,$rule)->getData();
		$res['source'] = 'qidian'; //源头
		return $res;
	}

	protected function getWebHtml($url){
		$guzzle = new Client;
		return $guzzle->get($url)->getBody()->getContents();
	}

}